const Dayjs = require("dayjs");
const MYSQL = require("../../sql/mysql");
const MysqlModule = require("../../sql/modules");
const Redis = require("../../sql/redis");
// 菜单表
const auth_menus = "menus";
// 行为表
const auth_action_sqlName = "auth_action";
// 角色表
const auth_role_sqlName = "auth_role";
// 接口表
const auth_path_sqlName = "auth_path";
// 角色菜单表
const auth_role_menu_sqlName = "auth_role_menu";
// 角色行为列表
const auth_role_action_sqlName = "auth_role_action";
// 角色接口表
const auth_role_path_sqlName = "auth_role_path";
// 角色数组过滤
async function rolesFilter(roles) {
  try {
    return {
      code: 0,
      msg: "获取成功",
      data: [],
    };
  } catch (error) {
    throw error;
  }
}
/**
 * 角色信息
 * @param {object} params
 * @param {string} params.user 用户id
 */
async function existRole(params = {}) { }
/**
 * 添加角色
 * @param {object} params
 * @param {string} params.user 用户id
 */
async function AddAuthRole(params = {}) {
  try {
    let { name, scope, comment } = params;
    if (!name) {
      throw { code: 500, msg: "添加失败，name不能为空" };
    } else if (!scope) {
      throw { code: 500, msg: "添加失败，scope不能为空" };
    }
    let Mysql_result = await MYSQL.promise().query(
      `SELECT * FROM ${auth_role_sqlName} WHERE name = ${name}`
    );
    let nameExist_result = Mysql_result[0];
    if (nameExist_result.length) {
      throw { code: 500, msg: "添加失败,name已存在" };
    }
    Mysql_result = await MYSQL.promise().query(
      `SELECT * FROM ${auth_role_sqlName} WHERE scope = ${scope}`
    );
    let actionExist_result = Mysql_result[0];
    if (actionExist_result.length) {
      throw { code: 500, msg: "添加失败,action已存在" };
    }
    let date_now = Dayjs(Date.now()).valueOf();
    Mysql_result = await MYSQL.promise().query(
      `INSERT INTO ${auth_action_sqlName} SET ?`,
      {
        name,
        scope,
        create_date: String(date_now),
        comment,
        state: 1,
      }
    );
    let insert_result = Mysql_result[0];
    let { affectedRows } = insert_result;
    if (affectedRows) {
      // Redis中添加角色信息

      return {
        code: 0,
        msg: "添加成功",
      };
    } else {
      throw { code: 500, msg: "添加失败,未知错误" };
    }
  } catch (error) {
    throw error;
  }
}
/**
 * 删除角色
 * @param {object} params
 * @param {string} params.user 用户id
 */
async function RemoveAuthRole(params = {}) {
  try {
    let { id } = params;
    let Conline = await MYSQL.promise().getConnection();
    let Delete = await MysqlModule.Delete(auth_role_sqlName, { id });
    // 查询完毕，释放池连接回池
    await Conline.release();
    return {
      code: 0,
      msg: "操作成功",
    };
  } catch (error) {
    throw error;
  }
}
/**
 * 角色列表(不分页)
 * @param {object} params
 * @param {string} params.user 用户id
 */
async function AuthRoleList(params = {}) {
  try {
    let Conline = await MYSQL.promise().getConnection();
    let list = await Conline.query(`SELECT * FROM ${auth_role_sqlName}`);
    // 查询完毕，释放池连接回池
    await Conline.release();
    return {
      code: 0,
      msg: "获取成功",
      data: list[0],
    };
  } catch (error) {
    throw error;
  }
}

/**
 * 角色列表(分页)
 * @param {object} params
 * @param {string} params.user 用户id
 */
async function AuthRoleListPage(params = {}) {
  try {
    return { code: 0, msg: "后" };
  } catch (error) { }
}
/**
 * 清空角色
 */
async function EmptyAuthRole(Request) {
  try {
  } catch (error) { }
}
/**
 * 修改角色
 * @param {object} params
 * @param {string} params.user 用户id
 */
async function UpdateAuthRole(params = {}) { }
/**
 * 角色信息
 * @param {object} params
 * @param {string} params.id 角色id
 */
async function AuthroleInfo(params = {}) {
  try {
    let { role } = params;
    // 查询Redis中是否存在该角色信息
    if (!role) {
      throw { code: 500, msg: "role参数不能为空" };
    }
    let Conline = await MYSQL.promise().getConnection();
    let RedisRoleInfo = await Redis.getConnection(role);
    let info = null;
    if (RedisRoleInfo) {
      info = JSON.parse(RedisRoleInfo);
    } else {
      let MysqlRoleInfoQuery = await Con.query(
        `SELECT * FROM ${auth_role_sqlName} WHERE id = ${role}`
      );
      let MysqlRoleInfo = MysqlRoleInfoQuery[0];
      info = MysqlRoleInfo;
    }
    await Conline.release();
    return {
      code: 0,
      msg: "获取成功",
      data: { role: role, info: RedisRoleInfo },
    };
  } catch (error) {
    throw { code: 500, msg: "未知错误" };
  }
}
/**
 * 角色添加操作行为权限
 * @param {object} params
 * @param {string} params.user 用户id
 */
async function AddRoleAction(params = {}) {
  try {
    let { actions, role } = params;
    if (!role) {
      throw { code: 500, msg: "添加失败,role不能为空" };
    } else if (!actions) {
      throw { code: 500, msg: "添加失败,actions不能为空" };
    }
  } catch (error) {
    throw error;
  }
}
/**
 * 角色删除行为
 * @param {object} params
 * @param {string} params.user 用户id
 */
async function RemoveRoleAction(params = {}) {
  try {
    let { actions, role } = params;
    if (!role) {
      throw { code: 500, msg: "添加失败,role不能为空" };
    } else if (!actions) {
      throw { code: 500, msg: "添加失败,actions不能为空" };
    }
    return await MysqlModule.Delete(auth_action_sqlName, {
      role,
      actions,
    });
  } catch (error) {
    throw error;
  }
}
/**
 * 角色添加接口
 * @param {object} params
 * @param {string} params.user 用户id
 */
async function AddRolePath(params = {}) {
  try {
    let { paths, role, path } = params;
  } catch (error) {
    throw error;
  }
}
/**
 * 角色删除接口
 * @param {object} params
 * @param {string} params.user 用户id
 */
async function RemoveRolePath(params = {}) {
  try {
    let { paths, role, path } = params;
  } catch (error) {
    throw error;
  }
}

/**
 * 获取所有菜单列表（不分页）
 */
async function MenusList(params = {}) {
  try {
    let Conline = await MYSQL.promise().getConnection();
    let list = await Conline.query(`SELECT * FROM ${auth_menus}`);
    await Conline.release();
    return {
      code: 0,
      msg: "获取成功",
      data: list[0],
    };
  } catch (error) {
    throw error;
  }
}

/**
 *  获取角色菜单权限列表（不分页）
 */
async function RoleMenusList(params = {}) {
  try {
    let Conline = await MYSQL.promise().getConnection();
    let list = await Conline.query(`SELECT * FROM ${auth_role_menu_sqlName}`);
    await Conline.release();
    return {
      code: 0,
      msg: "获取成功",
      data: list[0],
    };
  } catch (error) {
    throw error;
  }
}
/**
 *  获取角色接口权限列表（不分页）
 */
async function RolePathList(params = {}) {
  try {
    let Conline = await MYSQL.promise().getConnection();
    let list = await Conline.query(`SELECT * FROM ${auth_role_path_sqlName}`);
    await Conline.release();
    return {
      code: 0,
      msg: "获取成功",
      data: list[0],
    };
  } catch (error) {
    throw error;
  }
}

/**
 *  获取角色操作权限列表（不分页）
 */
async function RoleActionList(params = {}) {
  try {
    let Conline = await MYSQL.promise().getConnection();
    let list = await Conline.query(`SELECT * FROM ${auth_role_action_sqlName}`);
    await Conline.release();
    return {
      code: 0,
      msg: "获取成功",
      data: list[0],
    };
  } catch (error) {
    throw error;
  }
}
/**
 * 操作权限列表(分页)
 * @param {object} params
 * @param {string} params.page 用户id
 * @param {string} params.limit 用户id
 */
async function AuthActionList(Request) {
  try {
    let Query = Request.query;

    let {
      page = 1, // 当前页
      limit = 10, // 每页记录数量
    } = Query;

    limit = limit < 1 ? (limit = 1) : limit;

    page = page < 1 ? (page = 1) : page;

    let Conline = await MYSQL.promise().getConnection();

    // 获取列表数据
    let MysqlResult = await Conline.query(`
      SELECT * FROM ${auth_action_sqlName}
      LIMIT  ${limit} OFFSET ${(page - 1) * limit};
    `);

    let list = MysqlResult[0];

    // 获取数据总数 =====
    let totalResult = await Conline.query(
      `
       SELECT Count(*) AS total FROM ${auth_action_sqlName}
      `
    );

    let total = totalResult[0][0].total;

    let pages = Math.ceil(total / limit);

    await Conline.release();

    return {
      code: 0,
      msg: "获取成功",
      data: {
        page,
        pages,
        limit,
        total,
        list,
      },
    };
  } catch (error) {
    console.log(error);
    return {
      code: 500,
      msg: "获取失败,未知错误",
    };
  }
}

/**
 *  操作权限列表(不分页)
 *
 */
async function AuthActionAll() {
  try {
    let Conline = await MYSQL.promise().getConnection();
    let list = await Conline.query(`SELECT * FROM ${auth_action_sqlName}`);
    await Conline.release();
    return {
      code: 0,
      msg: "获取成功",
      data: list[0],
    };
  } catch (error) {
    throw error;
  }
}
/**
 * 添加操作权限
 * @param {object} params
 * @param {string} params.user 用户id
 */
async function AddAuthAction(params = {}) {
  try {
    let { name, action, comment } = params;
    if (!name) {
      throw { code: 500, msg: "添加失败，name不能为空" };
    } else if (!action) {
      throw { code: 500, msg: "添加失败，action不能为空" };
    }
    let Mysql_result = await MYSQL.promise().query(
      `SELECT * FROM ${auth_action_sqlName} WHERE name = ${name}`
    );
    let nameExist_result = Mysql_result[0];
    if (nameExist_result.length) {
      throw { code: 500, msg: "添加失败,name已存在" };
    }
    Mysql_result = await MYSQL.promise().query(
      `SELECT * FROM ${auth_action_sqlName} WHERE action = ${action}`
    );
    let actionExist_result = Mysql_result[0];
    if (actionExist_result.length) {
      throw { code: 500, msg: "添加失败,action已存在" };
    }
    let date_now = Dayjs(Date.now()).valueOf();
    Mysql_result = await MYSQL.promise().query(
      `INSERT INTO ${auth_action_sqlName} SET ?`,
      {
        name,
        action,
        create_date: String(date_now),
        comment,
        state: 1,
      }
    );
    let insert_result = Mysql_result[0];
    let { affectedRows } = insert_result;
    if (affectedRows) {
      return {
        code: 0,
        msg: "添加成功",
      };
    } else {
      throw { code: 500, msg: "添加失败,未知错误" };
    }
  } catch (error) {
    console.log("添加失败， ", error);
    throw error;
  }
}
/**
 * 删除操作权限
 * @param {object} params
 * @param {string} params.user 用户id
 */
async function RemoveAuthAction(params = {}) {
  let { id } = params;
  return await MysqlModule.Delete(auth_action_sqlName, { id });
}
/**
 * 修改操作权限
 * @param {object} params
 * @param {string} params.user 用户id
 */
async function UpdateAuthAction() { }
/**
 * 清空操作权限
 * @param {object} params
 * @param {string} params.user 用户id
 */
async function EmptyAuthAction() {
  return await MysqlModule.Delete(auth_action_sqlName);
}

/**
 * 接口权限列表（不分页）
 * @param {object} params
 * @param {string} params.user 用户id
 */
async function AuthPathListAll(params = {}) {
  try {
    let Conline = await MYSQL.promise().getConnection();
    let list = await Conline.query(`SELECT * FROM ${auth_path_sqlName}`);
    await Conline.release();
    return {
      code: 0,
      msg: "获取成功",
      data: list[0],
    };
  } catch (error) {
    throw error;
  }
}
/**
 * 接口权限列表（分页）
 * @param {object} params
 * @param {string} params.user 用户id
 */
async function AuthpathListPage(Request) {
  try {
    let query = Request.query;

    let { page = 1, limit = 10 } = query;

    limit = limit < 1 ? (limit = 1) : limit;
    page = page < 1 ? (page = 1) : page;

    // 获取Mysql池链接
    const Connection = await MYSQL.promise().getConnection();

    let StartMysql = await Connection.query(`
        SELECT  *
        FROM auth_path
        LIMIT ${(page - 1) * limit + "," + page * limit}
    `);

    // 取出数据列表
    let list = StartMysql[0];

    // 获取数据总数 =====
    let totalResult = await Connection.query(
      `
       SELECT Count(*) AS total FROM auth_path
      `
    );

    let total = totalResult[0][0].total;

    let pages = Math.ceil(total / limit);

    // 查询完毕，释放池连接回池
    await Connection.release();

    return {
      code: 0,
      msg: "获取成功",
      data: {
        pages,
        list,
        page: Number(page),
        limit: Number(limit),
        total: Number(total),
      },
    };
  } catch (error) {
    console.log(error);
    throw error;
  }
}
/**
 * 添加接口权限
 * @param {object} params
 * @param {string} params.name * 接口名称(唯一)
 * @param {string} params.path * 接口地址(唯一)
 * @param {string} params.type 接口类型
 * @param {string} params.comment 接口备注
 */
async function AddAuthPath(params = {}) {
  try {
    let { name, type, path, comment } = params;
    if (!type) {
      throw { code: 500, msg: "添加失败,type不能为空" };
    } else if (!name) {
      throw { code: 500, msg: "添加失败,name不能为空" };
    } else if (!path) {
      throw { code: 500, msg: "添加失败,path不能为空" };
    }
    let mysql_result = await MYSQL.promise().query(
      `
      SELECT * FROM ${auth_path_sqlName} WHERE type = ${type} and path = ${path}
      `
    );
    let exist_result = mysql_result[0];
    if (exist_result.length) {
      throw {
        code: 500,
        msg: "添加失败,存在相同记录",
      };
    }
    let create_date = Dayjs(Date.now()).valueOf();
    let state = 1;
    let query = `INSERT INTO ${sqlName} SET ? `;
    await MYSQL.promise().query(query, {
      name,
      path,
      comment,
      state,
      type,
      create_date,
    });
    return {
      code: 0,
      msg: "操作成功",
    };
  } catch (error) {
    throw error;
  }
}
/**
 * 删除接口权限（已完成）
 * @param {object} params
 * @param {string} params.id 接口id
 */
async function RemoveAuthPath(Request) {
  try {
    let Body = Request.body;
    let { id } = Body;
    if (!id) {
      throw {
        code: 500,
        msg: "id不能为空",
      };
    }
    // 获取Mysql池链接
    const Connection = await MYSQL.promise().getConnection();
    // 开始删除MYSQL
    let DeleteMysql = await Connection.query(`
      DELETE FROM auth_path WHERE id = ${id}
    `);
    // 查询完毕，释放池连接回池
    await Connection.release();
    // 判断是否删除成功
    let affectedRows = DeleteMysql[0].affectedRows;
    if (affectedRows) {
      return {
        code: 200,
        msg: "删除成功",
      };
    } else {
      throw {
        code: 500,
        msg: "删除失败",
      };
    }
  } catch (error) {
    console.log(error);
    throw error;
  }
}
/**
 * 修改接口权限（已完成）
 * @param {object} params
 * @param {string} params.user 用户id
 */
async function UpdateAuthPath(params = {}) {
  try {
    let { id, name, path, type, state, comment } = params;
    return await MysqlModule.Update(auth_path_sqlName, {
      where: `id = ${id}`,
      update: {
        name,
        path,
        type,
        state,
        comment,
      },
    });
  } catch (error) {
    throw error;
  }
}
/**
 * 清空接口权限（已完成）
 * @param {object} params
 * @param {string} params.user 用户id
 */
async function EmptyAuthPath() {
  return await MysqlModule.Delete(auth_path_sqlName);
}
/**
 * 角色菜单权限列表（已完成）
 * @param {object} params
 * @param {string} params.user 用户id
 */
async function AuthRoleMenus(params = {}) {
  try {
    let { user } = params;
    let { userInfo } = await userExist({ id: user });
    let userRole = userInfo.role;
    let userRoleType = typeof userRole;
    if (!userRole) {
      throw { code: 500, msg: "获取失败,roles为空" };
    }
    if (userRoleType === "string" || userRoleType === "number") {
      userRole = [Number(userRole)];
    } else if (Array.isArray(rolesType)) {
      if (!roles.length) {
        throw { code: 500, msg: "获取失败,roles为空" };
      }
    }

    let query = `

    SELECT * FROM ${auth_role_menu_sqlName} 

    RIGHT JOIN ${auth_menus} ON  

    ${auth_role_menu_sqlName}.menu_id = ${auth_menus}.id

    WHERE 

    role_id IN (${userRole.join()})

    `;

    let Mysql_result = await MYSQL.promise().query(query);

    let list = Mysql_result[0];

    return {
      code: 0,
      msg: "获取成功",
      data: list,
    };
  } catch (error) {
    console.log("获取菜单出错", error);
    throw error;
  }
}
/**
 * 角色菜单列表（全部）
 * @param {object} params
 * @param {string} params.user 用户id
 */
async function AuthRolesMenus(params = {}) { }
/**
 * 添加角色菜单权限
 * @param {object} params
 * @param {string} params.user 用户id
 */
async function AddAuthRoleMenu(params = {}) {
  try {
    let { role, menu } = params;

    if (!role) {
      throw { code: 500, msg: "role不能为空" };
    } else if (!menu) {
      throw { code: 500, msg: "menu不能为空" };
    }
  } catch (error) {
    throw error;
  }
}
/**
 * 删除角色菜单权限
 * @param {object} params
 * @param {string} params.user 用户id
 */
async function RemoveAuthRoleMenu(params = {}) { }
/**
 * 清空角色菜单权限
 * @param {object} params
 * @param {string} params.role 角色id
 */
async function EmptyAuthRoleMenu() {
  return await MysqlModule.Delete(auth_role_menu_sqlName);
}
/**
 * 删除菜单
 * @param {object} params 验证码id
 * @param {string} params.id 作废的验证码id
 * @param {string} params.state 作废后的验证码状态
 * @return {Promise<{code:number,msg:string} | {code:number,msg:string}>}
 */
async function DeleteMenu(params = {}) {
  try {

  } catch (error) {
    console.log(error);
    throw { code: 500, msg: "操作失败" };
  }
}
/**
 * 菜单信息
 * @param {object} params 验证码id
 * @param {string} params.id 作废的验证码id
 * @param {string} params.state 作废后的验证码状态
 * @return {Promise<{code:number,msg:string} | {code:number,msg:string}>}
 */
async function MenuInfo(params = {}) {
  try {
  } catch (error) {
    console.log(error);
    throw { code: 500, msg: "操作失败" };
  }
}
/**
 * 菜单列表
 * @param {object} params 验证码id
 * @param {string} params.id 作废的验证码id
 * @param {string} params.state 作废后的验证码状态
 * @return {Promise<{code:number,msg:string} | {code:number,msg:string}>}
 */
async function MenuList(params = {}) {
  try {
  } catch (error) {
    console.log(error);
    throw { code: 500, msg: "操作失败" };
  }
}
/**
 * 添加菜单
 * @param {object} params 验证码id
 * @param {string} params.id 作废的验证码id
 * @param {string} params.state 作废后的验证码状态
 * @return {Promise<{code:number,msg:string} | {code:number,msg:string}>}
 */
async function AddMenu() { }
module.exports = {
  AuthRoleListPage,
  rolesFilter,
  AuthRolesMenus,
  AddAuthPath,
  AddAuthAction,
  RemoveRoleAction,
  AuthRoleMenus,
  AddAuthRoleMenu,
  RemoveAuthRoleMenu,
  UpdateAuthPath,
  RemoveAuthAction,
  AuthPathListAll,
  RoleActionList,
  RoleMenusList,
  MenusList,
  RolePathList,
  AuthActionList,
  RemoveAuthPath,
  EmptyAuthPath,
  EmptyAuthAction,
  EmptyAuthRoleMenu,
  AddAuthRole,
  RemoveAuthRole,
  AuthRoleList,
  AuthActionAll,
  EmptyAuthRole,
  UpdateAuthRole,
  AuthroleInfo,
  AuthpathListPage,
};